﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Fetches.Fetch.Dto;

namespace Fetches.Fetch.Utils
{
    public class UrlUtils
    {
        public static string NormalizingUrl(string url, string refer)
        {
            return NormalizingUrl(url, refer, false);
        }

        public static string NormalizingUrl(string url, string refer, bool ajax)
        {
            try
            {
                Uri baseUrl;
                try
                {
                    baseUrl = new Uri(refer);
                }
                catch (UriFormatException)
                {
                    // the baseUrl is unsuitable, but the attribute may be abs on its own, so try that
                    return new Uri(url).AbsoluteUri;
                }
                if (!ajax && url.IndexOf("#") > 0)
                    url = url.Substring(0, url.IndexOf("#"));
                // workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
                if (url.StartsWith("?"))
                    url = baseUrl.AbsolutePath + url;
                var abs = new Uri(baseUrl, url);
                return encodeIllegalCharacterInUrl(abs.AbsoluteUri);
            }
            catch (Exception )
            {
                return "";
            }
        }

        /**
         * @param url url
         * @return new url
         */
        public static string encodeIllegalCharacterInUrl(string url)
        {
            return url.Replace(" ", "%20");
        }

        public static string GetHost(string url)
        {
            try
            {
               var uri=new Uri(url);
               return uri.Host;
            }
            catch (Exception)
            {
                return url;
            }
            
        }

        public static string RemoveProtocol(string url)
        {
            var patternForProtocal = new Regex("[\\w]+://");
            return patternForProtocal.Replace(url, "");
        }

        public static string GetDomain(string url)
        {
            string domain = RemoveProtocol(url);
            try
            {
                var uri = new Uri(domain);
                domain= uri.Host;
            }
            catch (Exception )
            {
                return url;
            }
            return RemovePort(domain);
        }

        public static string getRootDomain(string url)
        {
            string RE_TOP = "[\\w-]+\\.(com.cn|net.cn|gov.cn|org\\.nz|org.cn|com|net|org|gov|cc|biz|info|cn|co)\\b()*";
            string result = GetDomain(url);
            try
            {
                var matcher = new Regex(RE_TOP).Match(url);
                if (matcher.Success)
                {
                    result = matcher.Groups[1].Value;
                }
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
                
            }
            return result;
        }

        public static string RemovePort(string domain)
        {
            int portIndex = domain.IndexOf(":");
            if (portIndex != -1)
            {
                return domain.Substring(0, portIndex);
            }
            else
            {
                return domain;
            }
        }

        public static List<Request> ConvertToRequests(IList<string> urls)
        {
            var requestList = new List<Request>();
            foreach (var url in urls)
            {
                requestList.Add(new Request(url));
            }
            return requestList;
        }

        public static List<string> ConvertToUrls(IList<Request> requests)
        {
            List<string> urlList = new List<string>();
            foreach (var request in requests)
            {
                urlList.Add(request.Url.OriginalString);
            }
            return urlList;
        }

        public static string GetCharset(string contentType)
        {
            string pattern = @"(?i)\bcharset=(? <charset>[-a-zA-Z_0-9]+)";
            var matcher = Regex.Match(contentType, pattern);
            if (matcher.Success)
            {
                var charset = matcher.Groups[1].Value;
                return charset;
            }
            return null;
        }

        public static bool IsValidUrl(string s)
        {
            if (string.IsNullOrWhiteSpace(s) || s.Equals("#") || s.StartsWith("javascript:"))
            {
                return false;
            }
            return true;
        }

        /**
         * check whether input is a valid Uri
         *
         * @param urlString urlString
         * @return true means yes, otherwise no.
         * @author bob.li.0718@gmail.com
         */
        public static bool IsUrl(string urlString)
        {
            try
            {
                var uri = new Uri(urlString);
                return true;
            }
            catch (Exception )
            {
                return false;
            }
        }
    }
}
